package com.ruoyi.web.controller.client;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.*;
import java.io.IOException;

/**
 * @ClassName ImageUploadController
 * @Description TODO
 * @Author Mr、Liu
 * @Date 2025/6/24 14:04
 * @Version 1.0
 */
@RestController
@RequestMapping("/img")
public class ImageUploadController {

    @Value("${ruoyi.profile}")
    private String uploadDir;
    @Value("${server.port}")
    private int serverPort;

    /**
     * 图片上传接口存储到本地服务 作废
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @CrossOrigin
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择一个文件上传。", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名并清理路径，防止路径遍历
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            if (originalFileName.contains("..")) {
                return new ResponseEntity<>("无效的文件名。", HttpStatus.BAD_REQUEST);
            }

            // 检查文件是否是图片类型
            if (!isImageFile(originalFileName)) {
                return new ResponseEntity<>("只能上传图片文件。", HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            }

            // 动态生成路径，避免硬编码分隔符
            String imagesDir = uploadDir + File.separator + "images";
            // 确保上传目录存在，不存在则创建
            Path uploadPath = Paths.get(imagesDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一的文件名以避免覆盖（可选）
            String fileName = System.currentTimeMillis() + "_" + originalFileName;

            // 创建目标路径
            Path targetLocation = uploadPath.resolve(fileName).normalize();
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 生成文件访问URL
            String fileDownloadUri = File.separator+"profile"+File.separator+"images"+File.separator+ fileName;
            return new ResponseEntity<>(fileDownloadUri, HttpStatus.OK);
        } catch (IOException ex) {
            return new ResponseEntity<>("上传失败: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 辅助方法：判断文件是否为图片
    private boolean isImageFile(String fileName) {
        String[] imageExtensions = {"jpg", "jpeg", "png", "gif", "bmp"};
        String lowerCase = fileName.toLowerCase();
        for (String ext : imageExtensions) {
            if (lowerCase.endsWith("." + ext)) {
                return true;
            }
        }
        return false;
    }

    // 辅助方法：获取服务器的基础URL
    private String getServerUrl() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        String port = serverPort != 80 ? ":" + serverPort : "";
        return "http://" + hostAddress + port;
    }


}